<template>
	<view class="content">
		<!-- 顶部选项卡 -->
		<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
			<view 
				v-for="(item,index) in tabBars" :key="item.id"
				class="nav-item"
				:class="{current: index === tabCurrentIndex}"
				:id="'tab'+index"
				@click="changeTab(index)"
			>{{item.name}}</view>
		</scroll-view>
		
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="90" @refresh="onPulldownReresh" @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper 
				id="swiper"
				class="swiper-box" 
				:duration="300" 
				:current="tabCurrentIndex" 
				@change="changeTab"
			>
				<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">
					<scroll-view 
						class="panel-scroll-box" 
						:scroll-y="enableScroll" 
						@scrolltolower="loadMore"
						>
						<!-- 
							* 新闻列表 
							* 和nvue的区别只是需要把uni标签转为weex标签而已
							* class 和 style的绑定限制了一些语法，其他并没有不同
						-->
						<view class="news-list">
							<view v-for="(item, index) in tabItem.newsList" :key="index" class="news-item" @click="navToDetails(item)">
								<text :class="['title', 'title'+item.show_type]">{{item.title}}</text>
								<view v-if="item.images.length > 0" :class="['img-list', 'img-list'+item.show_type, item.images.length === 1 && item.show_type===3 ? 'img-list-single': '']">
									<view 
										v-for="(imgItem, imgIndex) in item.images" :key="imgIndex"
										:class="['img-wrapper', 'img-wrapper'+item.show_type, item.images.length === 1 && item.show_type===3 ? 'img-wrapper-single': '']"
									>
										<image class="img" :src="imgItem"></image>
										<view class="video-tip" v-if="item.videoSrc">
											<image class="video-tip-icon" src=""></image>
										</view>
									</view>
								</view>
								<!-- 空图片占位 -->
								<view v-else class="img-empty"></view>
								<view :class="['bot', 'bot'+item.show_type]">
									<text class="author">{{item.author_name}}</text>
									<text class="time">{{item.create_time}}</text>
								</view>
							</view>
						</view>
						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>
	</view>
</template>

<script>
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	let windowWidth = 0, scrollTimer = false, tabBar;
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore
		},
		data() {
			return {
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
			}
		},
		async onLoad() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},
		onNavigationBarButtonTap(val) {
			var type = val.float;
			if(type == 'left'){
				uni.navigateTo({
					url: '/pages/msg/index',
				});
			}
			if(type == 'right'){
				uni.navigateTo({
					url: '/pages/help/index',
				});	
			}
		},
		onNavigationBarSearchInputConfirmed (val) {
			uni.navigateTo({
				url: '/pages/news/search?keyword='+val.text,
			});	
		},
		methods: {
			/**
			 * 数据处理方法在vue和nvue中通用，可以直接用mixin混合
			 * 这里直接写的
			 * mixin使用方法看index.nuve
			 */
			//获取分类
			loadTabbars(){
				//获取基础参数
				// uni.showLoading({
				// 	title:"数据加载中",
				// 	mask:true
				// })
				let timestamp = this.helper.now();
				let sign = this.helper.setSign(['timestamp='+timestamp]);
				this.helper.req({
					api:"getTabBars",
					timestamp:timestamp,
					header:{sign:sign},
					method:'GET',
				}).then(res=>{
					let tabList = res.data.data.list;
					
					tabList.forEach(item=>{
						item.newsList = [];
						item.loadMoreStatus = 0;  //加载更多 0加载前，1加载中，2没有更多了
						item.refreshing = 0;
						item.page = 1;
						item.lastPage = 0;
					})
					
					this.tabBars = tabList;
					this.loadNewsList('add');
					console.log('执行到这里');
					uni.hideLoading();
				})
			},
			//新闻列表
			loadNewsList(type){
				let tabItem = this.tabBars[this.tabCurrentIndex];			
				//type add 加载更多 refresh下拉刷新
				console.log('type',type)
				if(type === 'add'){
					if(tabItem.loadMoreStatus === 2){
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				if(type === 'refresh'){
					tabItem.refreshing = true;
					tabItem.page = 1;
					tabItem.lastPage = 0;
					tabItem.newsList = []; //刷新前清空数组
				}
				// #endif
				//下拉刷新 关闭刷新动画

				let timestamp = this.helper.now();
				let sign = this.helper.setSign(['type='+tabItem.id,'page='+tabItem.page,'timestamp='+timestamp]);
				this.helper.req({
					api:"getNewsList",
					timestamp:timestamp,
					data:{type:tabItem.id,page:tabItem.page},
					header:{sign:sign},
					method:'GET',
				}).then(res=>{
					if(type === 'refresh'){
						this.$refs.mixPulldownRefresh;
						this.$refs.mixPulldownRefresh.endPulldownRefresh();
						// #ifdef APP-PLUS
						tabItem.refreshing = false;
						// #endif
						tabItem.loadMoreStatus = 0;
						
						uni.stopPullDownRefresh();
					}
					let current_page = res.data.data.list.current_page;
					let last_page = res.data.data.list.last_page;
					if(current_page == last_page){
						tabItem.loadMoreStatus = 2;
					}else{
						tabItem.page = current_page + 1;
					}
					tabItem.lastPage = last_page;
					tabItem.newsList = tabItem.newsList.concat(res.data.data.list.data);
					console.log('111')
					
				})
			},
			//新闻详情
			navToDetails(item){
				uni.navigateTo({
					url: `/pages/news/detail?news_id=${item.id}`
				})
			},
			
			//下拉刷新
			onPulldownReresh(){
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore(){
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable){
				if(this.enableScroll !== enable){
					this.enableScroll = enable;
				}
			},

			//tab切换
			async changeTab(e){
				
				if(scrollTimer){
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if(typeof e === 'object'){
					index = e.detail.current
				}
				if(typeof tabBar !== 'object'){
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0; 
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if(i === index){
						nowWidth = result.width;
					}
				}
				if(typeof e === 'number'){
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index; 
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(()=>{
					if (width - nowWidth/2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth/2 - windowWidth / 2;
					}else{
						this.scrollLeft = 0;
					}
					if(typeof e === 'object'){
						this.tabCurrentIndex = index; 
					}
					this.tabCurrentIndex = index; 
					
					
					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if(this.tabCurrentIndex !== 0 && tabItem.loaded !== true){
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 300)
				
			},
			//获得元素的size
			getElSize(id) { 
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
		}
	}
</script>

<style lang='scss'>
	page, .content{
		background-color: #f8f8f8;
		height: 100%;
		overflow: hidden;
	}
	.swiper-box{
		height: 100%;
	}
	.panel-scroll-box{
		height: 100%;
		
		.panel-item{
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}
</style>
